package net.aiotos.common.ice;

import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import net.aiotos.sdk.IOTOSysI;

import java.util.Date;

@Slf4j
public class RefreshSessionThread extends Thread
{
    public volatile boolean exit = false;
    private final IOTOSysI iotoSysI;
    private final long newTime = System.currentTimeMillis();

    public RefreshSessionThread(@NonNull final IOTOSysI iotoSysI)
    {
        this.setName(this.getClass().toString());
        this.iotoSysI = iotoSysI;
    }

    @SuppressWarnings("static-access")
    public void run()
    {
        log.info("路由守护服务启动[{}]", getId());
        Date date = new Date();
        while (!exit)
        {
            try
            {
                this.sleep(iotoSysI.getHeartbeat() * 1000);
                date.setTime(System.currentTimeMillis());
                iotoSysI.routerPrxRefreshSession();
                // log.info("runTime:{}, time:{}", (System.currentTimeMillis() - newTime) / 1000 / 60, date);
            } catch (Ice.ConnectTimeoutException ex) {
                log.warn("刷新心跳时，连接超时", ex);
            } catch (Ice.ConnectionLostException ex) {
                log.warn("刷新心跳时，连接丢失", ex);
            } catch (Ice.CommunicatorDestroyedException ex) {
                log.warn("上级已经挂了，可以自杀了");
                exit = true;
            } catch (Exception e)
            {
                e.printStackTrace();
            }
        }
        log.warn("runTime:{}, time:{}", (System.currentTimeMillis() - newTime) / 1000 / 60, date);
    }

}
